// ActionScript file
import com.adobe.serialization.json.*;
import com.fm618.flex.*;
import com.roguedevelopment.objecthandles.ObjectHandleEvent;
import com.roguedevelopment.objecthandles.ObjectHandles;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.Image;
import mx.events.ListEvent;
import mx.managers.PopUpManager;

public var g_id:int = 0;
public var s_id:String = '';

private var flag:Boolean=false;
private var URLCalendarRPC:String = SITEURL+'fm/getCalendar.php';
private var URLMyPhotoRPC:String = SITEURL+'fm/getMyPhoto.php';
private var url_MyMakedRPC:String = SITEURL+'fm/getMyMaked.php'; // 处理过的照片

// 标记 初始化执行httpservice
private var ss:SplashScreen;
private var flagScreen:int = 0;
private var HTTPSeCalendar:Boolean = false; //标志，remove popupwindow
private var HTTPSeMyPhoto:Boolean = false; //标志, remove popupwindow

[Bindable] public var myphoto:ArrayCollection = new ArrayCollection(); //用户上传的图片
[Bindable] private var Calendars:ArrayCollection = new ArrayCollection(); //一组日历


private function com():void
{
	this.s_id = this.parameters.sid;
	this.g_id = this.parameters.gid;
	this.setStyle("backgroundAlpha", "0");
	//pho.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
	//pho.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
	ccc.addEventListener(MouseEvent.MOUSE_OVER, setToBack);
	ccc.addEventListener(MouseEvent.MOUSE_OUT, setToFront);
}

/**
 * 初始化
 */
private function init():void
{
	ss = new SplashScreen();
	ss.percentWidth = 100;
	ss.percentHeight = 100;
	ss.label = 'Splash Screen';
	ss.setStyle('backgroundColor', '#ffff66');
	ss.setStyle('horizontalCenter', '0');
	ss.setStyle('verticalCenter', '0');
	ss.setTrackHeight(20);
	ss.alpha = 0.9;
	addChild(ss);
	//MyPhotoRPC.send();
	//CalendarRPC.send();
	ss.setLabel('加载日历');
	this.SendHttpService(this.URLCalendarRPC, null,this.CalendarRPCResult, '加载日历');
	
	ss.setLabel('读取照片');
	this.SendHttpService(this.URLMyPhotoRPC, null,this.getMyPhotoRPCResult, '读取照片');
	
	ss.setLabel('读取处理过的照片');
	this.SendHttpService(this.url_MyMakedRPC, null,this.MakedRPCResult, 'Maked');
}

/**
 * 结束Splash Screen
 */
private function removeSplash():void{
	//Alert.show(this.HTTPSeCalendar.toString());
	if(this.HTTPSeCalendar && this.HTTPSeMyPhoto){
	//if(this.HTTPSeCalendar){
		removeChild(ss);
	}
}

/*
private function startDragging(event:MouseEvent):void
{
	event.currentTarget.startDrag();
}

private function stopDragging(event:MouseEvent):void
{
	event.currentTarget.stopDrag();
}
*/
private function setToBack(event:MouseEvent):void{
	ccc.setChildIndex(d,0);
}
private function setToFront(event:MouseEvent):void{
	ccc.setChildIndex(d, ccc.numChildren-1);
}

private function over(event:MouseEvent):void
{
	var x:Number=mouseX;
	var y:Number=mouseY;
	var arr:Array=getObjectsUnderPoint(new Point(x, y));
	for each (var temp:Object in arr)
	{
		if (temp is Image)
		{
			if (temp.parent.parent.id == "d")
			{
				//(temp.parent.parent.parent).setChildIndex(temp.parent.parent,0);
				// 制作代理对象
				var t:Image = temp as Image;
				var z:ObjectHandles=new ObjectHandles();
				z.x=t.x;
				z.y=t.y;
				z.width=t.width;
				z.height=t.height;
				this.addChild(z);
				z.addEventListener(ObjectHandleEvent.OBJECT_RESIZING_EVENT, onEvent);
				z.addEventListener(ObjectHandleEvent.OBJECT_MOVING_EVENT, onEvent);
				z.addEventListener(ObjectHandleEvent.OBJECT_RESIZING_EVENT, function(e:ObjectHandleEvent):void{onEvent(e,t);});
				z.addEventListener(ObjectHandleEvent.OBJECT_MOVING_EVENT, onEvent);
				z.select();

			}
		}
	}
}

private function out(event:MouseEvent):void
{
	d.parent.setChildIndex(d, 1);
}

/*private function onEvent(event:ObjectHandleEvent):void
{
	// 同步原对象
	a.width=event.target.width;
	a.height=event.target.height;
	a.x=event.target.x;
	a.y=event.target.y;
}*/

private function onEvent(event:ObjectHandleEvent, img:Image):void
{
	// 同步原对象
	img.width=event.target.width;
	img.height=event.target.height;
	img.x=event.target.x;
	img.y=event.target.y;
}




/*
private function getCalendarRPCResult(event:ResultEvent):void{
	var tmp:Array=new Array();
	for each (var s:XML in event.result.info)
	{
		//trace(s.name);
		//tmp.push({name: s.name, urlx: s.urlx});
		Calendars.addItem({name: s.name, urlx: s.urlx});
	}
	
	//trace('上传图片加载完毕');
	//myphoto = MyUploadPhotos;
}
*/

/*
private function doStartDrag(event:MouseEvent):void{
	event.currentTarget.startDrag();
}
private function doStopDrag(event:MouseEvent):void{
	event.currentTarget.stopDrag();
	Alert.show(event.currentTarget.toString());
}*/

/**
 * 双击照片，添加到工作区
 */
private function addPhoto(event:ListEvent):void{
	//for(var tp in event.itemRenderer.data){
	//Alert.show(event.itemRenderer.data[tp]);//查询data中内容
	//}
	if(this.sourcePercent == 1){
		Alert.show('请先选择日历');
		return;
	}
	var my_date:Date = new Date();
	var img:Image = new Image();
	img.source = event.itemRenderer.data.urlx;
	img.id = 'cal_'+my_date.getTime();
	img.name = img.id;
	img.percentHeight = 100;
	img.percentWidth = 100;
	img.maintainAspectRatio = false;
	trace(img.source.toString());
	var oh:ObjectHandles = new ObjectHandles();
	oh.addChild(img);
	oh.allowRotate = true;
	oh.y = 88;
	oh.height = event.itemRenderer.data.height*this.sourcePercent;//与日历比例相等
	oh.width = event.itemRenderer.data.width*this.sourcePercent;//与日历比例相等
	oh.id = 'oh_'+img.id;
	oh.name = oh.id;
	//oh.alwaysMaintainAspectRatio = true;
	oh.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void{trace(e.charCode);removeMPhoto(e, oh.name);});
	//Alert.show(event.itemRenderer.data.width);
	ccc.addChild(oh);
	ccc.setChildIndex(oh, ccc.numChildren-1);
	//
	this.resultArr.push({id:img.id,
						url:event.itemRenderer.data.urlx,
						width:event.itemRenderer.data.width,
						height:event.itemRenderer.data.height,
						x:0,
						y:0});
	trace('add photo');
}
/**
 * 删除照片
 * @param e:KeyboardEvent 
 * @param ohnmae:String oh name
 */
private function removeMPhoto(e:KeyboardEvent, ohname:String):void{
	//Alert.show(e.charCode.toString());
	if(e.charCode == 127){
		ccc.removeChild(ccc.getChildByName(ohname));
	}
	//Alert.show(ccc.numChildren.toString());
}


/**
 * 工作区更换日历
 */
private function changeCal(event:ListEvent):void{
	d.source = event.itemRenderer.data.urlx;
	this.sourcePercent = d.width/event.itemRenderer.data.width;
	//for(var tp1 in event.itemRenderer.data){
	//Alert.show(event.itemRenderer.data[tp1]);
	//}
}
/**
 * “完成”的点击事件
 */
private function finish():void{
	var res1:Array = new Array();
	res1.push({type:'cal', url:d.source.toString(), percentw: sourcePercent, gid: g_id});
	//trace(ccc.getChildren());
	for(var t9:Number=0; t9<ccc.numChildren; t9++){
		//trace(ccc.getChildAt(t9));
		if(ccc.getChildAt(t9) is ObjectHandles){
			var t9s:String = ccc.getChildAt(t9).name.substr(3);
			var t9sa:Object = ccc.getChildAt(t9);
			var t9sao:ObjectHandles = t9sa as ObjectHandles;
			//trace(t9sao.getChildByName(t9s));
			var tmpobj:Image = t9sao.getChildByName(t9s) as Image;
			res1.push({type:'pho',url: tmpobj.source.toString(), width: tmpobj.width, height: tmpobj.height, x:tmpobj.parent.x, y:tmpobj.parent.y});
			
		}
	}
	trace(JSON.encode( res1));
	
	//Alert.show(d.source.toString());
	
	
	//数据
	var v:URLVariables = new URLVariables();
	v.elements = JSON.encode(res1);
	//请求
	var r:URLRequest = new URLRequest();
    r.url = SITEURL+"fm/savecalendar.php";  
    r.method = URLRequestMethod.POST;  
    r.data = v;
    var l:URLLoader = new URLLoader();  
    l.load(r);  
    l.addEventListener(Event.COMPLETE,FinishRequest);//注册请求完成后 响应获取数据事件方法
    
}

private function FinishRequest(e:Event):void{
	var l:URLLoader = URLLoader(e.target);  
    //var o:Object = URLUtil.stringToObject(String(l.data)); //使用URLUtil对将数据进行反序列化以方便使用  
    trace(l.data);
    if(l.data == 'OK'){
    	Alert.show('保存成功！');
    }
}


/**
 * 上传照片，弹出式对话框。
 */
private function ShowUploadMyPhotoDialog(e:MouseEvent):void{
	// 这里第三个参数 true 表示: 弹出myPanel窗口后, 是否可以对父级操作, 值为true时, 就会产生背景模糊的效果, 并不能对父级的东西进行操作
	var pop1:UploadPhotoM = UploadPhotoM(PopUpManager.createPopUp(this, UploadPhotoM, true)); 
	pop1.mapp = this;
	pop1.cbFunc = this.popFunction;
}
/**
 * 上传照片，弹出式对话框。
 */
private function ShowUploadMyPhotoDialog1(e:MouseEvent, tHandle:Object):void{
	// 这里第三个参数 true 表示: 弹出myPanel窗口后, 是否可以对父级操作, 值为true时, 就会产生背景模糊的效果, 并不能对父级的东西进行操作
	var pop1:UploadPhotoM = UploadPhotoM(PopUpManager.createPopUp(this, UploadPhotoM, true)); 
	pop1.mapp = tHandle;
	pop1.cbFunc = this.popFunction;
}
/**
 * 上传照片的回调函数
 */
 private function popFunction(value:Object):void{
 	this.HTTPSeMyPhoto = false;
 	ss = new SplashScreen();
	ss.percentWidth = 100;
	ss.percentHeight = 100;
	ss.label = 'Splash Screen';
	ss.setStyle('backgroundColor', '#ffff66');
	ss.setStyle('horizontalCenter', '0');
	ss.setStyle('verticalCenter', '0');
	ss.setTrackHeight(20);
	ss.alpha = 0.0;
	addChild(ss);
 	ss.setLabel('读取照片');
	this.SendHttpService(this.URLMyPhotoRPC, null,this.getMyPhotoRPCResult, '读取照片');
	trace(myphotoCanvas.getChildByName('temp1'));
	if(myphotoCanvas.getChildByName('temp1')!=null){
		myphotoCanvas.removeChild( myphotoCanvas.getChildByName('temp1'));//temp1是初始化时创建的提示未上传照片的canvas
	}
 }

